/*
 * Copyright (C) 2009 M. Hautle.
 * 
 * This file is part of TrackedBean.
 * 
 * TrackedBean is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * TrackedBean is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with TrackedBean. If not, see <http://www.gnu.org/licenses/>.
 */
package ch.trackedbean.copier.internal;

import ch.msoftch.internal.*;
import ch.simpleel.accessors.*;
import ch.trackedbean.copier.*;

/**
 * Object holding a deep mapping.
 * 
 * @author M. Hautle
 */
public class DeepMappingHolder extends AbstractSimpleMappingHolder {
    /** Flag indicating if {@link #copySrc2Dst(Object, Object, IMappingContext)} should override an object hold by the destination property. */
    protected final boolean overrideSrc;

    /** Flag indicating if {@link #copyDst2Src(Object, Object, IMappingContext)} should override an object hold by the destination property. */
    protected final boolean overrideDst;

    /** The type evaluator to use for {@link #copyToDestination(Object, Object, IMappingContext)} or null. */
    protected final ITypeEvaluator srcEvaluator;

    /** The type evaluator to use for {@link #copyToSource(Object, Object, IMappingContext)} or null. */
    protected final ITypeEvaluator dstEvaluator;

    /**
     * Default constructor.
     * 
     * @param src The source accessor
     * @param dst The destination accessor (on the object holding the mapping annotations)
     * @param overrideSrc Flag indicating if {@link #copySrc2Dst(Object, Object, IMappingContext)} should override an object hold by the source property
     * @param overrideDst Flag indicating if {@link #copyDst2Src(Object, Object, IMappingContext)} should override an object hold by the destination property
     * @param srcEvaluator The type evaluator to use for {@link #copyToSource(Object, Object, IMappingContext)} or null
     * @param dstEvaluator The type evaluator to use for {@link #copyToDestination(Object, Object, IMappingContext)} or null
     * @param readOnly Flag indicating if the mapping should be 'readonly' so that {@link #copyDst2Src(Object, Object, IMappingContext)} will not be executed
     * @param lazy Flag indicating if the property should be fetched lazy
     * @param profile The profile to which this mapping belongs
     */
    public DeepMappingHolder(IValueAccessor src, IValueAccessor dst, boolean overrideSrc, boolean overrideDst, ITypeEvaluator srcEvaluator,
            ITypeEvaluator dstEvaluator, boolean readOnly, boolean lazy, String profile) {
        super(src, dst, readOnly, lazy, profile);
        this.overrideSrc = overrideDst;
        this.overrideDst = overrideDst;
        this.srcEvaluator = srcEvaluator;
        this.dstEvaluator = dstEvaluator;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public void copyToDestination(Object src, Object dst, IMappingContext context) {
        try {
            final Object srcValue = srcProp.getValue(src, UNDEFINED);
            // skip if the source value was undefined
            if (srcValue == UNDEFINED)
                return;
            // set the destination to null if the source was null
            if (srcValue == null) {
                dstProp.setValue(dst, null);
                return;
            }
            final Class<?> type = getType(dstProp, srcEvaluator, srcValue);
            // lookup if the object was already converted
            Object dstValue = context.getElement(srcValue, type);
            if (dstValue == null) {
                // get the destination bean and copy the values (context registration will be done by the mapper call)
                dstValue = getCorrespondingBean(dstProp, type, dst, overrideDst);
                BeanMapperManager.copySrc2Dst(srcValue, dstValue, context);
            }
            dstProp.setValue(dst, dstValue);
        } catch (Exception e) {
            throw new TechnicalException("Error while copying " + this.srcProp.getPath() + " to " + this.dstProp.getPath(), e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public void copyToSource(Object src, Object dst, IMappingContext context) {
        try {
            final Object dstValue = dstProp.getValue(dst, UNDEFINED);
            // do nothing if there's no way to copy the value
            if (dstValue == UNDEFINED)
                return;
            // set the destination to null if the source was null
            if (dstValue == null) {
                srcProp.setValue(src, null);
                return;
            }
            final Class<?> type = getType(srcProp, dstEvaluator, dstValue);
            // lookup if the object was already converted
            Object srcValue = context.getElement(dstValue, type);
            if (srcValue == null) {
                // get the destination bean and copy the values (context registration will be done by the mapping call)
                srcValue = getCorrespondingBean(srcProp, type, src, overrideSrc);
                BeanMapperManager.copyDst2Src(dstValue, srcValue, context);
            }
            srcProp.setValue(src, srcValue);
        } catch (Exception e) {
            throw new TechnicalException("Error while copying " + this.dstProp.getPath() + " to " + this.srcProp.getPath(), e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object getDstValue(Object dst) {
        final Object dstValue = dstProp.getValue(dst, null);
        if (dstValue == null)
            return null;
        final Object srcValue = create(getType(srcProp, dstEvaluator, dstValue));
        return BeanMapperManager.copyDst2Src(dstValue, srcValue);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object getSrcValue(Object src) {
        final Object srcValue = srcProp.getValue(src, null);
        if (srcValue == null)
            return null;
        final Object dstValue = create(getType(dstProp, srcEvaluator, srcValue));
        return BeanMapperManager.copySrc2Dst(srcValue, dstValue);
    }

    /**
     * Returns an bean instance for the given property.<br>
     * If the property of the bean allready contains a non <code>null</code> value then simply this value is returned. Otherwise a new bean (of the property
     * type) will be instanciated.
     * 
     * @param acc The accessor
     * @param type The type to use for the property
     * @param dstBean The bean which owns the destination property
     * @param override If an allready existing property value should be overriden
     * @return A bean instance
     */
    @SuppressWarnings("unchecked")
    protected Object getCorrespondingBean(IValueAccessor acc, Class type, Object dstBean, boolean override) {
        if (override)
            return create(type);
        final Object dstValue = acc.getValue(dstBean, null);
        if (dstValue != null)
            return dstValue;
        return create(type);
    }

    /**
     * Creates an instance of the given type.
     * 
     * @param <T> The type
     * @param type The type
     * @return An instance of the given type
     */
    protected <T> T create(Class<T> type) {
        try {
            return type.newInstance();
        } catch (Exception e) {
            throw new TechnicalException("Error while creating " + type.getName(), e);
        }
    }

    /**
     * Returns the type to use for the given accessor.
     * 
     * @param acc The accessor for the property
     * @param evaluator The evaluator for the property
     * @param src The source value to 'convert'
     * @return The type to use
     */
    protected Class<?> getType(IValueAccessor acc, ITypeEvaluator evaluator, Object src) {
        if (evaluator != null)
            return evaluator.getCorrespondingType(src);
        return acc.getType();
    }
}